import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { UserEntity } from '@/api/create/interface'
import { fetchGetMtEnableDcs } from '@/api/create/dcs'
import Alert from '@/components/Alert'
import { t } from 'i18next'

export type DcsParamsEntity = {
	/**数据协作成员 */
	dcs_members: Array<UserEntity>
	/**0-关闭数据协作；1-管理方控制；2-自由协作*/
	mode: number
}
type StateStore = {
	/**数据协作开关*/
	enable: boolean
} & DcsParamsEntity
const initialState: StateStore = {
	enable: false,
	dcs_members: [],
	mode: 2,
}

type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	/**初始化 */
	init: (dcs: Partial<DcsParamsEntity> | null) => void
	/**切换权限控制模式 */
	changeMode: (_d: number) => void
	/**获取dcs数据 */
	getDcsData: () => undefined | DcsParamsEntity
	/**判断是否拥有数据权限*/
	getEnableMembers: (_d: Array<UserEntity>, callback?: (_d: Array<UserEntity>) => void) => void
}

export const useMeetingDcsStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		init: (dcs) => {
			if (dcs && dcs.mode && dcs.mode !== 0) {
				set({ enable: true, mode: dcs.mode, dcs_members: dcs.dcs_members ?? [] })
			} else {
				set({ dcs_members: [], mode: 2, enable: false })
			}
		},
		getDcsData: () => {
			const { enable, mode, dcs_members } = get()
			if (!enable) {
				return undefined
			} else {
				return {
					mode: mode,
					dcs_members: dcs_members.map((user) => {
						return {
							account: user.account,
							account_type: user.account_type,
							conf_e164: user.parent_id,
							name: user.name,
						}
					}),
				}
			}
		},
		changeMode: (d) => {
			set({ mode: d })
		},

		getEnableMembers: async (members, callback) => {
			let account_key_collection = members.map((x) => x.account).join(',')
			const res = await fetchGetMtEnableDcs(account_key_collection)
			if (res.success) {
				let dcsMembers: Array<UserEntity> = []
				let noAuthMt: Array<string> = []
				if (res.data && res.data.length > 0) {
					for (let i = 0; i < res.data.length; i++) {
						let flag = res.data[i]
						if (flag) {
							dcsMembers.push(members[i])
						} else {
							noAuthMt.push(members[i].name)
						}
					}

					if (noAuthMt.length > 0) {
						Alert(t('所选与会方{{name}}没有数据协作权限', { name: noAuthMt.join('、') }))
					}
					if (callback) {
						callback && callback(dcsMembers)
					}
				}
			} else {
				Alert(res.description)
			}
		},
	}))
)
